<!-- PhotoCapture.vue -->
<template>
    <div class="photo-capture">
      <div class="input-container">
        <input 
          type="text" 
          v-model="username" 
          placeholder="请输入用户名"
          @input="validateUsername"
        />
      </div>
  
      <div class="camera-container">
        <!-- 视频预览 -->
        <video 
          ref="video" 
          :class="{ hidden: hasPhoto }" 
          width="720" 
          height="560" 
          autoplay
        ></video>
        
        <!-- 拍照后的预览画布 -->
        <canvas 
          ref="canvas" 
          :class="{ hidden: !hasPhoto }" 
          width="720" 
          height="560"
        ></canvas>
      </div>
  
      <div class="button-container">
        <button 
          @click="startCamera" 
          :disabled="!isUsernameValid || isCameraActive"
        >
          打开摄像头
        </button>
        
        <button 
          @click="takePhoto" 
          :disabled="!isCameraActive || hasPhoto"
        >
          拍照
        </button>
        
        <button 
          @click="retake" 
          :disabled="!hasPhoto"
        >
          重拍
        </button>
        
        <button 
          @click="savePhoto" 
          :disabled="!hasPhoto || !isUsernameValid"
        >
          保存
        </button>
      </div>
  
      <!-- 状态提示 -->
      <div 
        v-if="statusMessage" 
        :class="['status-message', statusType]"
      >
        {{ statusMessage }}
      </div>
    </div>
  </template>
  
  <script>
  export default {
    name: 'PhotoCapture',
    data() {
      return {
        username: '',
        isUsernameValid: false,
        isCameraActive: false,
        hasPhoto: false,
        stream: null,
        statusMessage: '',
        statusType: 'info'
      }
    },
    methods: {
      validateUsername() {
        this.isUsernameValid = this.username.trim().length > 0
      },
  
      async startCamera() {
        try {
          this.stream = await navigator.mediaDevices.getUserMedia({ 
            video: {
              width: { ideal: 720 },
              height: { ideal: 560 }
            }
          })
          this.$refs.video.srcObject = this.stream
          this.isCameraActive = true
          this.updateStatus('摄像头已开启', 'success')
        } catch (err) {
          this.updateStatus('无法访问摄像头，请检查权限设置', 'error')
          console.error('摄像头错误:', err)
        }
      },
  
      takePhoto() {
        const canvas = this.$refs.canvas
        const video = this.$refs.video
        const context = canvas.getContext('2d')
  
        // 绘制视频帧到画布
        context.drawImage(video, 0, 0, canvas.width, canvas.height)
        this.hasPhoto = true
        this.updateStatus('照片已拍摄，请预览', 'success')
      },
  
      retake() {
        this.hasPhoto = false
        this.updateStatus('请重新拍摄', 'info')
      },
  
      async savePhoto() {
        try {
          const canvas = this.$refs.canvas
          const imageData = canvas.toDataURL('image/jpeg')
          
          // 创建一个 Blob
          const response = await fetch(imageData)
          const blob = await response.blob()
          
          // 创建 FormData
          const formData = new FormData()
          formData.append('username', this.username);
          formData.append('photo', blob, `${this.username}.jpg`);
          
          // 发送到后端
          const saveResponse = await fetch('http://localhost:3000/api/save-photo', { // 修改为后端URL
          method: 'POST',
          body: formData
        });
          
          if (saveResponse.ok) {
            this.updateStatus('照片保存成功！', 'success')
            // 清理现场
            this.cleanupCamera()
            // 重置状态
            this.hasPhoto = false
            this.username = ''
            this.isUsernameValid = false
            this.$router.push('/');
          } else {
            throw new Error('保存失败')
          }
        } catch (error) {
          this.updateStatus('保存照片失败，请重试', 'error')
          console.error('保存错误:', error)
        }
      },
  
      cleanupCamera() {
        if (this.stream) {
          this.stream.getTracks().forEach(track => track.stop())
          this.stream = null
        }
        this.isCameraActive = false
      },
  
      updateStatus(message, type = 'info') {
        this.statusMessage = message
        this.statusType = type
      }
    },
    
    beforeUnmount() {
      this.cleanupCamera()
    },
  }
  </script>
  
  <style scoped>
  .photo-capture {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 20px;
    padding: 20px;
    max-width: 800px;
    margin: 0 auto;
  }
  
  .input-container {
    width: 100%;
    max-width: 300px;
  }
  
  input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    font-size: 16px;
  }
  
  input:focus {
    border-color: #1890ff;
    outline: none;
    box-shadow: 0 0 0 2px rgba(24,144,255,0.2);
  }
  
  .camera-container {
    position: relative;
    width: 720px;
    height: 560px;
    background-color: #f5f5f5;
    border-radius: 8px;
    overflow: hidden;
  }
  
  video, canvas {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .hidden {
    display: none;
  }
  
  .button-container {
    display: flex;
    gap: 10px;
    margin-top: 20px;
  }
  
  button {
    padding: 10px 20px;
    font-size: 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    background-color: #1890ff;
    color: white;
    transition: all 0.3s;
  }
  
  button:hover:not(:disabled) {
    background-color: #40a9ff;
  }
  
  button:disabled {
    background-color: #d9d9d9;
    cursor: not-allowed;
  }
  
  .status-message {
    padding: 10px 20px;
    border-radius: 4px;
    margin-top: 20px;
  }
  
  .status-message.success {
    background-color: #f6ffed;
    border: 1px solid #b7eb8f;
    color: #52c41a;
  }
  
  .status-message.error {
    background-color: #fff2f0;
    border: 1px solid #ffccc7;
    color: #ff4d4f;
  }
  
  .status-message.info {
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    color: #1890ff;
  }
  </style>